<template>
  <div>
    <van-uploader :max-count="maxCount" :after-read="afterRead" v-model="fileList" @delete="deleteImg">
      <img v-if="typeImage" class="file_img" :src="typeImage" alt="">
			<!-- <van-button icon="photo" type="primary">上传图片</van-button> -->
		</van-uploader>
  
    <van-overlay :show="showOverlay" >
      <van-loading class="middle-loading" type="spinner">图片上传中...</van-loading>
    </van-overlay>
  </div>
</template>

<script>
import Vue from 'vue'
import uploader from 'vant/lib/uploader'
import { Loading } from 'vant'
import { Overlay } from 'vant'
// import 'vant/lib/index.css'

Vue.use(Overlay)
Vue.use(Loading)
Vue.use(uploader)

import { uploadImgs } from '@/api/community/article'
export default Vue.extend({
  name: 'UploadImg',
  props: {
    maxCount: {
      type: [Number, String],
      default: 5
    },
    typeImage: {
      type: String,
      default: ''
    },
    previewSize: {
      type: String,
      default: '80px'
    }
  },
  data() {
    return {
      fileList: [],
      showOverlay: false
      // maxCount: 5
    }
  },
  methods: {
    /**
     * 返回布尔值
     */
    afterRead(file) {
      const form = new FormData()
      // console.log(file, 1222, this.fileList)
      form.append('file', file.file)
      this.showOverlay = true
      setTimeout(() => { // 假如接口没有反应 10s关闭遮罩
        this.showOverlay = false
      }, 10000)
      uploadImgs(form).then(res => {
        this.showOverlay = false
        const fileList = this.fileList
        if (res.status === 1) {
          fileList[fileList.length - 1].content = res.data.pic_url
          this.$emit('uploadImgList', this.fileList)
        } else {
          const index = fileList.length - 1
          this.fileList.splice(index, 1)
          this.$Error('上传失败, 请重新上传')
        }
      }).catch(() => {
        this.$Error('上传失败, 请重新上传')
        this.showOverlay = false
        const fileList = this.fileList
        const index = fileList.length - 1
        this.fileList.splice(index, 1)
      })
    },
    /**
     * 删除图片
     */
    deleteImg() {
      this.$emit('uploadImgList', this.fileList)
    },

    // 清空图片预览
    clearImg() {
      this.fileList = []
    }
  }
})
</script>
<style lang="scss">
.file_img {
  width: 100%
}
</style>
